<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="品牌中文名" prop="name" label-width="100px">
        <el-input
          style="width: 200px"
          v-model="queryParams.name"
          placeholder="请输入品牌中文名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌英文名" prop="ename" label-width="100px">
        <el-input
          style="width: 200px"
          v-model="queryParams.ename"
          placeholder="请输入品牌英文名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌编码" prop="code" label-width="100px">
        <el-input
          style="width: 200px"
          v-model="queryParams.code"
          placeholder="请输入品牌编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="品牌产地" prop="addr" label-width="100px">
        <el-input
          style="width: 200px"
          v-model="queryParams.addr"
          placeholder="请输入品牌产地"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item
        label="品牌国家"
        prop="nation"
        label-width="100px"
        v-show="showSearch"
      >
        <el-input
          style="width: 200px"
          v-model="queryParams.nation"
          placeholder="请输入品牌国家"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item> -->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:brand:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['goods:brand:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['goods:brand:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['goods:brand:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleAddExport"
          >导入</el-button
        >
      </el-col>
      <!-- 操作手册 -->
      <operationManual />
      <right-toolbar
        :showSearch.sync="showSearch"
        @handleQuery="handleQuery"
        @resetQuery="resetQuery"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="brandList"
      @selection-change="handleSelectionChange"
      v-adaptive="{ bottomOffset: 50 }"
      height="100px"
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="品牌中文名" align="center" prop="name" />
      <el-table-column label="品牌英文名" align="center" prop="ename" />
      <el-table-column label="品牌logo" align="center">
        <template slot-scope="scope">
          <el-row :gutter="10">
            <el-image :src="scope.row.imgUrl" class="Image"></el-image>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="品牌编码" align="center" prop="code" />
      <!-- <el-table-column label="品牌产地" align="center" prop="addr" /> -->
      <el-table-column label="品牌国家" align="center" prop="nation" />
      <el-table-column
        label="品牌描述"
        align="center"
        prop="remark"
        show-overflow-tooltip=""
      />
      <el-table-column
        label="状态"
        align="center"
        prop="closeFlag"
        :formatter="closeFlagStatusFormat"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown" @command="handleCommand">
              <el-dropdown-item
                command="修改"
                @click.native="handleUpdate(scope.row)"
                ><el-button
                  size="mini"
                  type="text"
                  v-show="scope.row.closeFlag === '0'"
                  v-hasPermi="['goods:brand:edit']"
                  >修改</el-button
                >
              </el-dropdown-item>
              <el-dropdown-item
                command="删除"
                @click.native="handleDelete(scope.row)"
                ><el-button
                  size="mini"
                  type="text"
                  v-show="scope.row.closeFlag === '0'"
                  v-hasPermi="['goods:brand:remove']"
                  >删除</el-button
                >
              </el-dropdown-item>
              <el-dropdown-item
                command="停用"
                @click.native="handleClose(scope.row)"
                ><el-button
                  size="mini"
                  type="text"
                  v-show="scope.row.closeFlag === '0'"
                  v-hasPermi="['goods:brand:close']"
                  >停用</el-button
                >
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <!-- <el-button -->
          <!-- size="mini" -->
          <!-- type="text" -->
          <!-- icon="el-icon-edit" -->
          <!-- v-show="scope.row.closeFlag === '0'" -->
          <!-- @click="handleUpdate(scope.row)" -->
          <!-- v-hasPermi="['goods:brand:edit']" -->
          <!-- >修改</el-button> -->
          <!-- <el-button -->
          <!-- size="mini" -->
          <!-- type="text" -->
          <!-- icon="el-icon-delete" -->
          <!-- v-show="scope.row.closeFlag === '0'" -->
          <!-- @click="handleDelete(scope.row)" -->
          <!-- v-hasPermi="['goods:brand:remove']" -->
          <!-- >删除</el-button> -->
          <!-- <el-button -->
          <!-- size="mini" -->
          <!-- type="text" -->
          <!-- icon="el-icon-close" -->
          <!-- @click="handleClose(scope.row)" -->
          <!-- v-show="scope.row.closeFlag === '0'" -->
          <!-- v-hasPermi="['goods:brand:close']" -->
          <!-- >停用</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 导入对话框 -->
    <el-dialog
      :visible.sync="upload.open"
      width="400px"
      append-to-body
      @close="closeDialogLead"
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :on-change="aaa"
        :file-list="fileList"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size: 12px" @click="importTemplate"
            >下载模板</el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品品牌对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="520px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="品牌名称" prop="name" label-width="100px">
          <el-input v-model="form.name" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌英文名" prop="ename" label-width="100px">
          <el-input v-model="form.ename" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌编码" prop="code" label-width="100px">
          <el-input
            v-model="form.code"
            :disabled="addCode"
            placeholder="请输入品牌编码"
          />
        </el-form-item>
        <!-- <el-form-item label="品牌产地" prop="addr" label-width="100px">
          <el-input v-model="form.addr" placeholder="请输入品牌产地" />
        </el-form-item> -->
        <el-form-item label="品牌国家" prop="nation" label-width="100px">
          <el-input v-model="form.nation" placeholder="请输入品牌国家" />
        </el-form-item>
        <el-form-item label="品牌描述" prop="remark" label-width="100px">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="品牌logo" prop="images" label-width="100px">
          <el-upload
            :multiple="true"
            :http-request="uploadFile"
            action="#"
            list-type="picture-card"
            accept="image/*"
            :file-list="form.images"
            :auto-upload="true"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <i class="el-icon-download"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="handleDialog" width="520px">
      <div>
        以下数据是新增数据，<span style="color: red"
          >点击确认更新和新增，点击取消不更新和新增</span
        >
      </div>
      <el-table :data="insertList" border>
        <el-table-column
          prop="brandName"
          align="center"
          label="品牌名称"
        ></el-table-column>
        <el-table-column
          prop="brandEnName"
          align="center"
          label="品牌英文名称"
        ></el-table-column>
        <el-table-column
          prop="brandNation"
          align="center"
          label="品牌国家"
        ></el-table-column>
        <el-table-column
          prop="brandRemark"
          align="center"
          label="品牌描述"
        ></el-table-column>
      </el-table>
      <div>
        以下数据是更新数据，<span style="color: red"
          >点击确认更新和新增，点击取消不更新和新增</span
        >
      </div>
      <el-table :data="handleDialogList" border>
        <el-table-column
          prop="brandName"
          align="center"
          label="品牌名称"
        ></el-table-column>
        <el-table-column
          prop="brandEnName"
          align="center"
          label="品牌英文名称"
        ></el-table-column>
        <el-table-column
          prop="brandNation"
          align="center"
          label="品牌国家"
        ></el-table-column>
        <el-table-column
          prop="brandRemark"
          align="center"
          label="品牌描述"
        ></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleDialogSubmitForm"
          >确 定</el-button
        >
        <el-button @click="handleDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <div v-if="activate"></div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  listBrand,
  getBrand,
  delBrand,
  addBrand,
  close,
  updateBrand,
  handleImportDataUpdate,
} from "@/api/goods/brand";
import { uploadFile } from "@/api/system/file";
import download from "@/utils/download";
import __ from "lodash";

export default {
  name: "Brand",
  components: {},
  data() {
    return {
      activate: true,
      // 缩略图url
      dialogImageUrl: "",
      // 是否显示文件缩略图
      dialogVisible: false,
      // 是否禁用
      disabled: false,
      addCode: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的品牌名称
      names: [],
      closeFlagOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 商品品牌表格数据
      brandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      handleDialog: false,
      handleDialogList: [],
      insertList: [],
      handleMsg: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        closeFlag: null,
        ename: null,
        code: null,
        addr: null,
        nation: null,
        remark: null,
      },
      // 表单参数
      form: {},
      upload: {
        // 是否显示弹出层（订单导入）
        open: false,
        // 弹出层标题（订单导入）
        // 生上传弹窗类型 importOrder 导入订单 importQuery 导入查询
        type: "importOrder",
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
          "fkmalls-client": "CBEC-ADMIN",
          biz_code: "CBI",
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/goods/brand/importData",
      },
      // 表单校验
      rules: {
        name: [
          {
            required: true,
            message: "请输入品牌中文名",
            trigger: "blur",
          },
        ],
        ename: [
          {
            required: true,
            message: "请输入品牌英文名",
            trigger: "blur",
          },
        ],
        nation: [
          {
            required: true,
            message: "请输入品牌国家",
            trigger: "blur",
          },
        ],
        // addr: [
        //   {
        //     required: true,
        //     message: "请输入品牌产地",
        //     trigger: "blur",
        //   },
        // ],
      },
    };
  },
  //触发回流
  activated() {
    this.activate = false;
    setTimeout(() => {
      this.activate = true;
    });
  },
  created() {
    this.getList();
    //开票状态
    this.getDicts("sys_close_flag").then((response) => {
      this.closeFlagOptions = response.data;
    });
  },
  methods: {
    handleAddExport() {
      this.upload.open = true;
    },
    //数据导入清空
    closeDialogLead() {
      // this.fileList;
      console.log(this.fileList, 1111);
      this.$refs.upload.clearFiles();
    },
    //下载模板
    importTemplate() {
      this.download(
        "/goods/brand/importTemplate",
        {},
        `品牌导入-${new Date().getTime()}.xlsx`
      );
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.priceCheckFlag = false;
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.handleDialogList = response.data?.update;
      this.insertList = response.data?.insert;
      if (response.data === null) {
        this.$alert(response.msg, "导入结果", {
          dangerouslyUseHTMLString: true,
        });
      } else {
        this.handleMsg = response.msg;
        this.handleDialog = true;
      }
      this.getList();
    },
    async handleDialogSubmitForm() {
      const data = this.handleDialogList.concat(this.insertList);
      const res = await handleImportDataUpdate(data);
      if (res.code === 200) {
        this.handleDialog = false;
        this.getList();
        this.msgSuccess("导入成功");
      }
    },
    closeFlagStatusFormat(row, column) {
      return this.selectDictLabel(this.closeFlagOptions, row.closeFlag);
    },
    /** 查询商品品牌列表 */
    getList() {
      this.loading = true;
      listBrand(this.queryParams).then((response) => {
        this.brandList = response.data;
        this.total = response.total;
        this.loading = false;
      });
    },
    uploadFile(options) {
      const formData = new FormData();
      formData.append("file", options.file);
      uploadFile(formData).then((response) => {
        if (response.data instanceof Array) {
          response.data.forEach((data) => {
            this.form.images.push(data);
          });
        } else {
          this.form.images.push(response.data);
        }
      });
    },
    // 删除图片
    handleRemove(file) {
      this.__.remove(this.form.images, (img) => {
        return img.id === file.id;
      });
      this.form.images = [...this.form.images];
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 下载图片
    handleDownload(file) {
      download(file.url, file.name);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        code: null,
        ename: null,
        imgUrl: null,
        addr: null,
        nation: null,
        remark: null,
        delFlag: null,
        closeFlag: null,
        companyId: null,
        companyName: null,
        deptId: null,
        deptName: null,
        ownerId: null,
        ownerName: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null,
        images: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.names = selection.map((item) => item.name);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.addCode = true;
      this.title = "添加商品品牌";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.addCode = false;
      const id = row.id || this.ids;
      getBrand(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品品牌";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBrand(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBrand(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //停用
    handleClose(row) {
      this.$confirm(
        '是否确认停用品牌名称为"' + row.name + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return close(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.name || this.names;
      this.$confirm('是否确认删除品牌名称为"' + names + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delBrand(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "goods/brand/export",
        {
          ...this.queryParams,
        },
        `goods_brand.xlsx`
      );
    },
  },
};
</script>
<style scoped>
.Image {
  width: 60px;
  height: 60px;
  vertical-align: middle;
}
</style>
